Technical Q&AJava 12 - Using
|
import java.awt.Frame; import java.awt.FileDialog; import java.io.File; import java.io.IOException; import com.apple.mrj.MRJFileUtils; public class ExecTest extends Frame { public static void main(String[ ] args) { new ExecTest(); System.exit(0); } public ExecTest() { String url = "http://developer.apple.com/java/"; try { //Attempt to let MRJ do all the work for us. MRJFileUtils.openURL(url); //If this was successful, then we need not go on. return; } catch (IOException exc) { //This can occur if problems arise while attempting to open the URL. } catch (NoSuchMethodError err) { //This can occur when earlier versions of MRJ are used which //do not support the openURL method. } catch (NoClassDefFoundError err) { //This can occur under runtime environments other than MRJ. } //If we make it here, MRJ was unsuccessful in opening the URL, and //we need to do it the hard way, using Runtime.exec. String browserName; //Set up a FileDialog for the user to locate the browser to use. FileDialog fileDialog = new java.awt.FileDialog(this); fileDialog.setMode(FileDialog.LOAD); fileDialog.setTitle("Choose the browser to use:"); fileDialog.setVisible(true); //Retrieve the path information from the dialog and verify it. String resultPath = fileDialog.getDirectory(); String resultFile = fileDialog.getFile(); if(resultPath != null && resultPath.length()!= 0 && resultFile != null && resultFile.length() != 0) { File file = new File(resultPath + resultFile); if(file != null) { browserName = file.getPath(); try { //Launch the browser and pass it the desired URL Runtime.getRuntime().exec(new String[] {browserName, url}); } catch (IOException exc) { exc.printStackTrace(); } } } } } |
The method openURL()
has been added to the class com.apple.mrj.MRJFileUtils since
MRJ SDK 2.2 EA2. OpenURL
uses Internet Config to attempt to open the preferred browser and direct it to the specified URL.
public static void openURL (String url) throws IOException;
This example should be refined, if used in a real setting, to cache the browser information and only ask the user if the cached browser could not be located.
A more sophisticated approach that would not require the user to choose the browser could use JConfig to obtain the default browser information.
As an alternative to JConfig for the sole purpose of opening a URL in
the user's default browser, one should consider BrowserLauncher
by Eric Albert. BrowserLauncher
is a Java class designed to allow programmers to open a user's default web browser
entirely through Java, without requiring that any supplemental libraries be present
and without stepping outside of JDK 1.1. BrowserLauncher
is free
for commercial and non-commercial use.